//
//  RequestApi.m
//  MexicoLoan
//
//  Created by wxp on 2025/2/26.
//

#import "RequestApi.h"

@implementation RequestApi

#pragma mark - request type
+ (void)postUrl:(NSString *)URL
       delegate:(id <RequestDelegate> _Nullable)delegate
     parameters:(NSDictionary * _Nullable)parameters
        success:(void (^)(NSDictionary * response, id mark))success
        failure:(void (^)(NSString * errorStr, id mark))failure{
    [self postUrl:URL delegate:delegate parameters:parameters returnALL:false isGet:false constructingBodyWithBlock:nil success:success failure:failure];
}

+ (void)getUrl:(NSString *)URL
      delegate:(id <RequestDelegate> _Nullable)delegate
    parameters:(NSDictionary * _Nullable)parameters
       success:(void (^)(NSDictionary * response, id mark))success
       failure:(void (^)(NSString * errorStr, id mark))failure{
    [self postUrl:URL delegate:delegate parameters:parameters returnALL:false isGet:true constructingBodyWithBlock:nil success:success failure:failure];
}

// post
+ (void)postUrl:(NSString *)URL
       delegate:(id <RequestDelegate> _Nullable)delegate
     parameters:(NSDictionary * _Nullable)parameters
      returnALL:(BOOL)returnAll
        success:(void (^)(NSDictionary * response, id mark))success
        failure:(void (^)(NSString * errorStr, id mark))failure{
    [self postUrl:URL delegate:delegate parameters:parameters returnALL:returnAll isGet:false constructingBodyWithBlock:nil success:success failure:failure];
}

// get
+ (void)getUrl:(NSString *)URL
      delegate:(id <RequestDelegate> _Nullable)delegate
    parameters:(NSDictionary * _Nullable)parameters
     returnALL:(BOOL)returnAll
       success:(void (^)(NSDictionary * response, id mark))success
       failure:(void (^)(NSString * errorStr, id mark))failure{
    [self postUrl:URL delegate:delegate parameters:parameters returnALL:returnAll isGet:false constructingBodyWithBlock:nil success:success failure:failure];
}

// 上传图片
+ (void)postUrl:(NSString *)URL
       delegate:(id <RequestDelegate> _Nullable)delegate
     parameters:(NSDictionary * _Nullable)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
        success:(void (^)(NSDictionary * response, id mark))success
        failure:(void (^)(NSString * errorStr, id mark))failure
{
    [self postUrl:URL delegate:delegate parameters:parameters returnALL:true isGet:false constructingBodyWithBlock:block success:success failure:failure];
}

#pragma mark - 请求执行
+ (void)postUrl:(NSString *)URL
       delegate:(id <RequestDelegate> _Nullable)delegate
     parameters:(NSDictionary * _Nullable)parameters
      returnALL:(BOOL)returnAll
          isGet:(BOOL)isGet
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
        success:(void (^)(NSDictionary * response, id mark))success
        failure:(void (^)(NSString * errorStr, id mark))failure{
    [[LocationService sharedInstance] startUpdatingLocation];
    [[SessionManager sharedInstance] setValueForHTTPHeaderFieldWithUrl:URL];
    parameters = [self setInitHead:parameters];
    NSString * urlNew = [URL hasPrefix:@"http"] ? URL : [NSString stringWithFormat:@"%@%@",URL_HEAD,URL];
    [GlobalMethod performSelector:@"protocolWillRequest" delegate:delegate];
    [self switchRequest:urlNew parameters:parameters isGet:isGet constructingBodyWithBlock:block success:^(NSURLSessionDataTask *task, id responseObject) {
        [self endRefresh:delegate];
        NSDictionary * dicResponse =  responseObject;
        if (dicResponse == nil ) {
            [self requestFailDelegate:delegate errorStr:@"fail" errorCode:@"0" failure:failure];
            return ;
        }
        // success
        if([@([dicResponse[RESPONSE_CODE] integerValue]) isEqualToNumber:RESPONSE_CODE_200]){
            [self requestSuccessDelegate:delegate responseDic:returnAll?dicResponse:dicResponse[RESPONSE_DATA] success:success];
            return;
        }
        // login
        if([@([dicResponse[RESPONSE_CODE] integerValue]) isEqualToNumber:RESPONSE_CODE_LOGINFAILURE]){
            [GlobalMethod showAlert:@"¡Favor de iniciar sesión!"];
            [GlobalMethod relogin];
            return;
        }
        
        // block request - fail
        NSString * message = dicResponse[RESPONSE_MESSAGE];
        if([dicResponse[RESPONSE_CODE] integerValue] == 500){
            if (![GlobalMethod checkWhetherShowMessageWithUrl:urlNew]){
                message = @"Red ocupada";
            }
        }
        [self requestFailDelegate:delegate errorStr:message errorCode:isNum(dicResponse[RESPONSE_CODE])?[NSString stringWithFormat:@"%@",dicResponse[RESPONSE_CODE]]:@"0" failure:failure];
        return;
        
    } failure:^(NSURLSessionDataTask *task, NSError *error){
        [self endRefresh:delegate];
        // block - network - fail
        [self requestFailDelegate:delegate errorStr:@"Red no disponible" errorCode:@"0" failure:failure];
    }];
}

+ (void)switchRequest:(NSString *)URLString
           parameters:(id)parameters
                isGet:(BOOL)isGet
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
              success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
              failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure{
    NSURLSessionDataTask * task;
    if (isGet == true) {
        task = [[SessionManager sharedInstance] GET:URLString parameters:parameters progress:nil success:success failure:failure];
    } else if (block == nil) {
        task = [[SessionManager sharedInstance] POST:URLString parameters:parameters progress:nil success:success failure:failure];
    } else {
        task = [[SessionManager sharedInstance] POST:URLString parameters:parameters constructingBodyWithBlock:block progress:nil success:success failure:failure];
    }
}

#pragma mark - success
+ (void)requestSuccessDelegate:(id<RequestDelegate>)delegate responseDic:(NSDictionary *)responseDic success:(void (^)(NSDictionary * response, id mark))success{
    //走回调 请求成功
    [GlobalMethod performSelector:@"protocolDidRequestSuccess" delegate:delegate];
    if (success != nil) {
        success(responseDic,nil);
    }
}

#pragma mark - fail
+ (void)requestFailDelegate:(id<RequestDelegate>)delegate errorStr:(NSString *)strError errorCode:(NSString *)errorCode failure:(void (^)(NSString * errorStr, id mark))failure{
    [GlobalMethod performSelector:@"protocolDidRequestFailure:" delegate:delegate object:strError isHasReturn:false];
    if (failure != nil) {
        failure(strError,errorCode);
    }
}

+ (void)endRefresh:(id)delegate{
    if (delegate != nil && [delegate respondsToSelector:@selector(endRefreshing)]) {
        [delegate performSelector:@selector(endRefreshing)];
    }
}

+ (NSMutableDictionary *)setInitHead:(NSDictionary *)dicParameters  {
    if (dicParameters == nil){
        dicParameters = [NSDictionary dictionary];
    }
    NSMutableDictionary * muDic = [NSMutableDictionary dictionaryWithDictionary:dicParameters];
    return muDic;
}

@end
